package com.bai.localshop.controller.user;

import com.bai.localshop.pojo.dto.*;
import com.bai.localshop.pojo.vo.AddressVO;
import com.bai.localshop.result.Result;
import com.bai.localshop.service.AddressBookService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/user/address")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址
     */
    @PostMapping
    public Result<Long> addAddress(@Valid @RequestBody AddressAddDTO addressAddDTO) {
        log.info("新增地址");
        Long addressId = addressBookService.addAddress(addressAddDTO);
        return Result.success(addressId);
    }

    /**
     * 修改地址
     */
    @PutMapping
    public Result<String> updateAddress(@Valid @RequestBody AddressUpdateDTO addressUpdateDTO) {
        log.info("修改地址，地址ID: {}", addressUpdateDTO.getId());
        addressBookService.updateAddress(addressUpdateDTO);
        return Result.success();
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteAddress(@PathVariable Long id) {
        log.info("删除地址，地址ID: {}", id);
        addressBookService.deleteAddress(id);
        return Result.success();
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/default")
    public Result<String> setDefaultAddress(@Valid @RequestBody SetDefaultAddressDTO setDefaultAddressDTO) {
        log.info("设置默认地址，地址ID: {}", setDefaultAddressDTO.getAddressId());
        addressBookService.setDefaultAddress(setDefaultAddressDTO.getAddressId());
        return Result.success();
    }

    /**
     * 查询地址详情
     */
    @GetMapping("/{id}")
    public Result<AddressVO> getAddressDetail(@PathVariable Long id) {
        AddressVO addressVO = addressBookService.getAddressDetail(id);
        return Result.success(addressVO);
    }

    /**
     * 查询当前用户地址列表
     */
    @GetMapping("/list")
    public Result<List<AddressVO>> getUserAddressList() {
        List<AddressVO> addressList = addressBookService.getUserAddressList();
        return Result.success(addressList);
    }

    /**
     * 查询默认地址
     */
    @GetMapping("/default")
    public Result<AddressVO> getDefaultAddress() {
        AddressVO defaultAddress = addressBookService.getDefaultAddress();
        return Result.success(defaultAddress);
    }
}
